package stendcontrol;

import java.util.ArrayList;

public class ExperimentContainer {

    private ArrayList<Experiment> exp_lst = new ArrayList<Experiment>();
    private ArrayList<ExperimentContainerListener> listeners =
            new ArrayList<ExperimentContainerListener>();
    private int cur_exp = -1;

    /**
     * Operation
     *
     * @return Experiment
     */
    public Experiment getCurExp() {
        if (cur_exp != -1) {
            return exp_lst.get(cur_exp);
        } else {
            StendLogger.log(StendLogger.MSG_ERROR, "Current Experiment "
                    + "not setup.");
            return null;
        }
    }

    private void updateListeners(){
        for(ExperimentContainerListener ecl:listeners){
            if(ecl!=null){
                ecl.changed();
            }else{
                listeners.remove(ecl);
            }
        }
    }
    /**
     * Operation
     *
     * @param exp
     * @return
     */
    public void addExp(Experiment exp) {
        exp_lst.add(exp);
        updateListeners();
    }

    /**
     * Operation
     *
     * @param exp
     * @return
     */
    public void removeExp(Experiment exp) {
        if (exp_lst.contains(exp)) {
            exp_lst.remove(exp);
            updateListeners();
        } else {
            StendLogger.log(StendLogger.MSG_ERROR, "Can't remove experement:"
                    + exp);
        }
    }

    public void removeAllExp() {
        exp_lst.clear();
        updateListeners();
    }

    /**
     * Operation
     *
     * @param n
     * @return Experiment
     */
    public Experiment getExp(int n) {
        if (n >= 0 && n < exp_lst.size()) {
            return exp_lst.get(n);
        } else {
            StendLogger.log(StendLogger.MSG_ERROR, "Bad index n:" + n + ". "
                    + "Can't get Experiment");
            return null;
        }
    }

    /**
     * Operation
     *
     * @return int
     */
    public int getSize() {
        return exp_lst.size();
    }

    /**
     * Operation
     *
     * @param nexp
     * @return
     */
    public void setCurExp(int nexp) {
        if (nexp > 0) {
        }
    }

    public int getIndexOfChild(Experiment exp) {
        return exp_lst.indexOf(exp);
    }

    @Override
    public String toString() {
        return "Эксперименты Кол-во:" + exp_lst.size();
    }
    
    public void addListener(ExperimentContainerListener ecl){
        listeners.add(ecl);
    }
    
    public void removeListener(ExperimentContainerListener ecl){
        listeners.remove(ecl);
    }
    
    public void removeAllListeners(){
        listeners.clear();
    }
}
